import {loginByUsername, logout, getUserInfo} from '@/api/login'
import {getToken, setToken, setRoles, getRoles, setUser, getUser, removeToken} from '@/utils/auth'
import {
  SET_USERINFO,
  SET_UID,
  SET_TOKEN,
  SET_INTRODUCTION,
  SET_SETTING,
  SET_STATUS,
  SET_NAME,
  SET_AVATAR,
  SET_ROLES,
  SET_ROLENAME,
  SET_COMPANY
} from './mutation-types'

const user = {
  state: {
    uid: '',
    userinfo: {},
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    company: '',
    roles: [],
    rolename: [],
    setting: {
      articlePlatform: []
    }
  },
  mutations: {
    [SET_USERINFO]: (state, userinfo) => {
      state.userinfo = userinfo
    },
    [SET_UID]: (state, uid) => {
      state.uid = uid
    },
    [SET_TOKEN]: (state, token) => {
      state.token = token
    },
    [SET_INTRODUCTION]: (state, introduction) => {
      state.introduction = introduction
    },
    [SET_SETTING]: (state, setting) => {
      state.setting = setting
    },
    [SET_STATUS]: (state, status) => {
      state.status = status
    },
    [SET_NAME]: (state, name) => {
      state.name = name
    },
    [SET_AVATAR]: (state, avatar) => {
      state.avatar = avatar
    },
    [SET_ROLES]: (state, roles) => {
      state.roles = roles
    },
    [SET_ROLENAME]: (state, rolename) => {
      state.rolename = rolename
    },
    [SET_COMPANY]: (state, company) => {
      state.company = company
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({commit}, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(res => {
          if (res.code == 0) {
            const data = res.data
            setToken(data.auth)  //登录成功后将token存储在cookie之中 用户获取信息传token到服务器,来验证用户的信息
            commit('SET_TOKEN', data.auth)
            setUser(data) //存入cookie
            resolve(data);
          } else {
            // console.log(res);
          }
        }).catch(error => {
          reject(error)
        })

      })
    },

    // 获取用户信息 未使用
    GetUserInfo({commit, state}) {
      // console.log('cookie-获取用户信息')
      const info = JSON.parse(getUser());
      // console.log(222, info);
      // todo
      commit('SET_USERINFO', info)
      commit('SET_NAME', info.user.username)
      commit('SET_AVATAR', info.user.headerUrl)
      commit('SET_INTRODUCTION', info.user.position)
      commit('SET_COMPANY', info.user.company)
      if (info.roleList && info.roleList.length > 0) { // 验证返回的roles是否是一个非空数组
        let aa = info.roleList.map(item => item.roleCode)
        // console.log(aa); //["超级管理员", "普通用户"]
        let roles = info.roleList.map(item => item.roleCode);
        let rolesName = info.roleList.map(item => item.roleName);
        commit('SET_ROLES', roles) //["superadmin", "ordinary"]
        commit('SET_ROLENAME', rolesName)  //["超级管理员", "普通用户"]
        setRoles(roles)
        return roles
      } else {
        return false
      }
    },
    // 获取用户信息 未使用
    GetUserInfo2({commit, state}) {
      // console.log('获取用户信息')
      return new Promise((resolve, reject) => {
        getUserInfo(state.token).then(response => {
          if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
            reject('error')
          }
          const data = response.data

          if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.roles)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }

          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({commit, state}) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_ROLENAME', [])
          commit('SET_UID', '')
          commit('SET_NAME', '')
          commit('SET_AVATAR', '')
          commit('SET_INTRODUCTION', '')
          commit('SET_USERINFO', {})
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({commit}) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_ROLENAME', [])
        commit('SET_UID', '')
        commit('SET_NAME', '')
        commit('SET_AVATAR', '')
        commit('SET_INTRODUCTION', '')
        commit('SET_USERINFO', {})
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({commit, dispatch}, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          dispatch('GenerateRoutes', data) // 动态修改权限后 重绘侧边菜单
          resolve()
        })
      })
    }
  }
}

export default user
